import conf from '@/config';

// 判断JSON字符串
export const isJSON = (v) => {
  if (!v) {
    return false;
  }
  if (typeof v === 'number') {
    return false;
  }
  if (v.charAt(0) !== '{') {
    return false;
  }

  try {
    JSON.parse(v);
    return true;
  } catch (e) {
    return false;
  }
};

// JSON字符串转json对象
export const setJSON = (v) => {
  if (v) {
    return JSON.parse(v);
  }
  return false;
};

// 判断是否为图片
export const isIMG = (v) => {
  if (!v) {
    return false;
  }
  if (v.indexOf('jpg', v.length - 4) > 0 || v.indexOf('png', v.length - 4) > 0) {
    return true;
  }
  return false;
};

// 判断电话号码格式
export const isPhone = (v) => {
  const reg = /^((13[0-9])|(14[5|7])|(15([0-9]))|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$/g;
  const bool = reg.test(v);

  return bool;
};

// 参数序列化
export const queryString = (obj) => {
  const arr = [];

  for (const [k, v] of Object.entries(obj)) {
    arr.push(`${k}=${v}`);
  }

  return arr.join('&');
};

// 判断身份证号
export const isIdCard = (v) => {
  const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  const bool = reg.test(v);

  return bool;
};

// 判断正整数
export const isInt = (v) => {
  const reg = /^(0|[1-9]\d*)\b/gm;
  const bool = reg.test(v);

  return bool;
};

// 判断邮箱
export const isEmail = (v) => {
  const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  const bool = reg.test(v);

  return bool;
};

// 图片获取地址
export const requestImgUrl = (url) => {
  const token = (localStorage.userObject ? JSON.parse(localStorage.userObject).token : '');
  const imgurl = `${conf.baseURL}/edges/oss/redirect?file=${url}&__token__=${token}`;
  return imgurl;
};

// 参数中文乱码
export const setCHUrl = (val) => {
  const newVal = encodeURI(val);
  // return decodeURI(val);
  return newVal;
};
